<template>
    <div>
        <!-- 面包屑导航区域 -->
        <el-breadcrumb separator-class="el-icon-arrow-right">
            <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
            <el-breadcrumb-item>用户管理</el-breadcrumb-item>
            <el-breadcrumb-item>用户列表</el-breadcrumb-item>
        </el-breadcrumb>
        <!-- 卡片视图区域 -->
        <el-card>
            <el-row :gutter="20">
                <el-col :span="8">
                    <el-input placeholder="请输入内容" v-model="queryInfo.query" clearable @clear="getUserList">
                        <el-button slot="append" icon="el-icon-search" @click="getUserList"></el-button>
                    </el-input>
                </el-col>
                <el-col :span="4">
                    <el-button type="primary" @click="addDialogVisible=true">添加用户</el-button>
                </el-col>
            </el-row>
            <!-- 表格区域 -->
            <el-table :data="userlist" border stripe>
                <el-table-column type="index"></el-table-column>
                <el-table-column prop="username" label="姓名"></el-table-column>
                <el-table-column prop="email" label="邮箱"></el-table-column>
                <el-table-column prop="mobile" label="电话"></el-table-column>
                <el-table-column prop="role_name" label="角色"></el-table-column>
                <el-table-column prop="mg_state" label="状态">
                    <!-- 作用域插槽开关 -->
                    <template slot-scope="scope">
                        <el-switch v-model="scope.row.mg_state" @change="ChangeState(scope.row)"></el-switch>
                    </template>
                </el-table-column>
                <el-table-column label="操作" width="180px">
                    <template slot-scope="scope">
                        <el-button type="primary" icon="el-icon-edit" size="mini" @click="editDialog(scope.row.id)">
                        </el-button>
                        <el-button type="danger" icon="el-icon-delete" size="mini" @click="removeUser(scope.row.id)">
                        </el-button>
                        <!-- 按钮上边的文字提示 -->
                        <el-tooltip effect="dark" content="分配角色" placement="top" :enterable='false'>
                            <el-button type="warning" icon="el-icon-setting" size="mini" @click="setUsers(scope.row)">
                            </el-button>
                        </el-tooltip>
                    </template>
                </el-table-column>
            </el-table>
            <!-- 底部的分页 -->
            <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
                :current-page="queryInfo.pagenum" :page-sizes="[1, 2, 5, 10]" :page-size="queryInfo.pagesize"
                layout="total, sizes, prev, pager, next, jumper" :total="total">
            </el-pagination>
        </el-card>
        <!-- 添加用户的对话框 -->
        <el-dialog title="添加用户" :visible.sync="addDialogVisible" width="50%" @close="addDialogClosed">
            <!-- 主体区域 -->
            <el-form :model="addForm" :rules="addFormRules" ref="ruleFormRef" label-width="70px">
                <el-form-item label="用户名" prop="username">
                    <el-input v-model="addForm.username"></el-input>
                </el-form-item>
                <el-form-item label="密码" prop="password">
                    <el-input v-model="addForm.password"></el-input>
                </el-form-item>
                <el-form-item label="邮箱" prop="email">
                    <el-input v-model="addForm.email"></el-input>
                </el-form-item>
                <el-form-item label="手机" prop="mobile">
                    <el-input v-model="addForm.mobile"></el-input>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="addDialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="addUser">确 定</el-button>
            </span>
        </el-dialog>
        <!-- 点击编辑按钮弹出的对话框 -->
        <el-dialog title="修改用户信息" :visible.sync="editDialogVisible" width="70%" @close='editDialogclosed'>
            <el-form :model="editForm" :rules="editRules" ref="editruleForm" label-width="70px">
                <el-form-item label="用户名">
                    <el-input v-model="editForm.username" disabled></el-input>
                </el-form-item>
                <el-form-item label="邮箱">
                    <el-input v-model="editForm.email"></el-input>
                </el-form-item>
                <el-form-item label="手机号">
                    <el-input v-model="editForm.mobile"></el-input>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="editDialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="editUserInfo">确 定</el-button>
            </span>
        </el-dialog>
        <!-- 点击分配角色按钮弹出的对话框 -->
        <el-dialog title="提示" :visible.sync="UserdialogVisible" width="50%" @close="closeUsersDialog">
            <div>
                <p>当前的用户:{{UsersInfo.username}}</p>
                <p>当前的角色:{{UsersInfo.role_name}}</p>
                <p>分配新角色:
                    <el-select v-model="selectUsers" placeholder="请选择">
                        <el-option v-for="item in UsersList" :key="item.id" :label="item.roleName" :value="item.id">
                        </el-option>
                    </el-select>
                </p>
            </div>
            <span slot="footer" class="dialog-footer">
                <el-button @click="UserdialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="selectNewUsers">确 定</el-button>
            </span>
        </el-dialog>
    </div>
</template>
<script>
    export default {
        data() {
            //自定义的验证规则，用于验证邮箱，手机号
            const checkEmail = (rule, value, callback) => {
                const regEmail =
                    /^[a-zA-Z0-9_.-]+@[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)*\.[a-zA-Z0-9]{2,6}$/
                if (regEmail.test(value)) {
                    return callback()
                }
                callback(new Error('请输入合法的邮箱'))
            }
            const checkMobile = (rule, value, callback) => {
                const regMobile =
                    /^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/
                if (regMobile.test(value)) {
                    return callback()
                }
                callback(new Error('请输入合法的手机号'))
            }
            return {
                //用户列表的查询参数对象
                queryInfo: {
                    query: '',
                    //当前的页数
                    pagenum: 1,
                    //当前每页显示多少条数据
                    pagesize: 2
                },
                //用户列表总的数据条数
                total: 0,
                //用户列表数据
                userlist: [],
                //控制添加用户对话框的显示与隐藏
                addDialogVisible: false,
                //控制编辑对话框的显示与隐藏
                editDialogVisible: false,
                //添加用户的表单数据对象
                addForm: {
                    username: '',
                    password: '',
                    email: '',
                    mobile: ''
                },
                //添加用户的表单验证规则对象
                addFormRules: {
                    username: [{
                            required: true,
                            message: '请输入用户名',
                            trigger: 'blur'
                        },
                        {
                            min: 3,
                            max: 5,
                            message: '长度在 3 到 5 个字符',
                            trigger: 'blur'
                        }
                    ],
                    password: [{
                            required: true,
                            message: '请输入密码',
                            trigger: 'blur'
                        },
                        {
                            min: 6,
                            max: 15,
                            message: '长度在 6 到 15 个字符',
                            trigger: 'blur'
                        }
                    ],
                    email: [{
                        required: true,
                        message: '请输入邮箱',
                        trigger: 'blur'
                    }, {
                        validator: checkEmail,
                        trigger: 'blur'
                    }],
                    mobile: [{
                        required: true,
                        message: '请输入手机号',
                        trigger: 'blur'
                    }, {
                        validator: checkMobile,
                        trigger: 'blur'
                    }]

                },
                //存放获取的需要修改的用户数据对象
                editForm: {},
                //修改用户信息的表单验证规则对象
                editRules: {
                    email: [{
                        required: true,
                        message: '请输入邮箱',
                        trigger: 'blur'
                    }, {
                        validator: checkEmail,
                        trigger: 'blur'
                    }],
                    mobile: [{
                        required: true,
                        message: '请输入手机号',
                        trigger: 'blur'
                    }, {
                        validator: checkMobile,
                        trigger: 'blur'
                    }]
                },
                //控制分配角色对话框的显示与隐藏
                UserdialogVisible: false,
                //需要被分配角色的用户信息
                UsersInfo: {},
                //存放获取的角色信息
                UsersList: [],
                //已经选中的角色id
                selectUsers:''

            }
        },
        created() {
            this.getUserList();
        },
        methods: {
            async getUserList() {
                const {
                    data: res
                } = await this.$http.get('users', {
                    params: this.queryInfo
                });
                console.log(res);
                if (res.meta.status !== 200) {
                    this.$message.error(res.meta.msg);
                }
                this.userlist = res.data.users;
                this.total = res.data.total;
            },
            //监听每页多少条数据改变的事件
            handleSizeChange(newsize) {
                console.log(newsize);
                this.queryInfo.pagesize = newsize;
                this.getUserList();

            },
            //监听页码值改变的事件
            handleCurrentChange(newpage) {
                console.log(newpage);
                this.queryInfo.pagenum = newpage;
                this.getUserList();

            },
            // 监听switch开关的状态改变的事件
            async ChangeState(mgstate) {
                console.log(mgstate);
                const {
                    data: res
                } = await this.$http.put(`users/${mgstate.id}/state/${mgstate.mg_state}`);
                console.log(res);
                if (res.meta.status !== 200) {
                    //如果修改用户状态失败，就复原为原来的状态
                    mgstate.mg_state = !mgstate.mg_state;
                    return this.$message.error('修改用户状态失败');
                }
                this.$message.success('修改用户状态成功')
            },
            //关闭添加用户的对话框，清空对话框中的表单数据
            addDialogClosed() {
                this.$refs.ruleFormRef.resetFields();
            },
            //点击添加用户对话框的确定按钮，触发的函数
            addUser() {
                this.$refs.ruleFormRef.validate(async valid => {
                    console.log(valid);
                    if (!valid) return;
                    //发起添加用户的网络请求
                    const {
                        data: res
                    } = await this.$http.post('users', this.addForm);
                    console.log(res);
                    if (res.meta.status !== 201) {
                        this.$message.error('添加用户失败');
                    }
                    this.$message.success('添加用户成功');
                    //隐藏添加用户的对话框
                    this.addDialogVisible = false;
                    //重新获取用户列表数据
                    this.getUserList();
                })

            },
            //点击编辑用户的按钮触发的事件
            async editDialog(id) {
                const {
                    data: res
                } = await this.$http.get('users/' + id);
                console.log(res);
                if (res.meta.status !== 200) {
                    return this.$message.error('获取用户数据失败')
                }
                this.editForm = res.data;
                console.log(this.editForm,"111");
                this.editDialogVisible = true
            },
            //编辑用户的表单对话框关闭重置表单
            editDialogclosed() {
                this.$refs.editruleForm.resetFields();
            },
            //点击确定按钮，提交修改的用户表单数据
            editUserInfo() {
                //点击确定按钮提交之前进行表单的预验证
                this.$refs.editruleForm.validate(async valid => {
                    console.log(valid);
                    if (!valid) return;
                    const {
                        data: res
                    } = await this.$http.put('users/' + this.editForm.id, {
                        email: this.editForm.email,
                        mobile: this.editForm.mobile
                    });
                    console.log(res);
                    if (res.meta.status !== 200) {
                        return this.$message.error('修改用户信息失败')
                    }
                    //关闭修改用户的对话框
                    this.editDialogVisible = false;
                    //重新查询用户列表数据
                    this.getUserList();
                    this.$message.success('修改用户信息成功')
                })
            },
            //点击删除按钮，删除用户
            async removeUser(id) {
                const resultConfirm = await this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).catch(error => {
                    return error;
                })
                console.log(resultConfirm);
                if (resultConfirm !== 'confirm') {
                    return this.$message.info('用户取消了删除')
                }
                //删除用户，发起请求
                const {
                    data: res
                } = await this.$http.delete('users/' + id);
                console.log(res);
                if (res.meta.status !== 200) {
                    return this.$message.error('删除用户失败')
                }
                this.$message.success('删除用户成功')
                this.getUserList();


            },
            //点击分配角色按钮触发的事件
            async setUsers(users) {
                this.UsersInfo = users;
                console.log(this.UsersInfo,"1111");
                //发起请求，获取角色信息
                const {
                    data: res
                } = await this.$http.get('roles');
                console.log(res);
                if (res.meta.status !== 200) {
                    this.$message.error('获取角色信息失败')
                }
                console.log(res);
                this.UsersList = res.data;
                this.UserdialogVisible = true;
            },
            //点击分配角色的对话框确定按钮，触发的事件
            async selectNewUsers(){
                if(!this.selectUsers){
                    this.$message.error('请选择需要重新分配的角色')
                }
                const {data:res}=await this.$http.put(`users/${this.UsersInfo.id}/role`,{
                    rid:this.selectUsers
                })
                console.log(res);
                if(res.meta.status!==200){
                    return this.$message.error('更新角色信息失败')
                }
                this.$message.success('更新角色信息成功');
                this.getUserList();
                this.UserdialogVisible=false;


            },
            //监听分配角色对话框的关闭事件
            closeUsersDialog(){
                this.selectUsers='';
                this.UsersInfo={};
            }
        }
    }
</script>